-- 定义 nasm 插件任务
task("nasm")
do
  -- 设置类别为插件
  set_category("plugin")
  -- 设置插件菜单
  set_menu({
    usage = "xmake nasm [target]",
    description = "Generate a nasm project with boot.asm, .asm-lsp.toml, Makefile, and xmake.lua",
    options = {
      { nil, "target", "v", nil, "a00" },
    },
  })

  -- 插件运行入口
  on_run(function()
    import("core.base.option")

    -- 获取目标项目名称，默认为 "a00"
    local target_name = option.get("target") or "a00"
    -- xmake nasm a01
    -- if option.get("target") then
    -- target_name = option.get("target")
    -- end
    print("生成项目: %s", target_name)
    local project_root = path.join(os.curdir(), target_name)

    -- 定义项目目录结构
    local project_dirs = {
      path.join(project_root, "src", "boot"),
    }

    -- 创建目录
    for _, dir in ipairs(project_dirs) do
      os.mkdir(dir)
      print("创建目录: %s", dir)
    end

    -- 1. 创建 src/boot/boot.asm
    local boot_asm_content = [[mov ax, cs
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7c00

mov ax, 3
int 0x10

mov bp, message + 0x7c00
mov ax, 0x1301
mov bx, 0x0007
mov cx, message_len
mov dx, 0
int 0x10

jmp $

message:
  db "Hello, world!", 0
message_len equ $ - message

times 510-($-$$) db 0
db 0x55, 0xaa
]]
    local boot_asm_file = path.join(project_root, "src", "boot", "boot.asm")
    io.writefile(boot_asm_file, boot_asm_content)
    print("生成文件: %s", boot_asm_file)

    -- 2. 创建 .asm-lsp.toml
    local asm_lsp_content = [[# 汇编语言服务器配置
[default_config]
version = "0.10.0"
assembler = "nasm"
instruction_set = "x86/x86-64"

[default_config.opts]
compiler = "nasm"
compile_flags_txt = [
    "-o",
    "/dev/null",
]
diagnostics = true
default_diagnostics = false
]]
    local asm_lsp_file = path.join(project_root, ".asm-lsp.toml")
    io.writefile(asm_lsp_file, asm_lsp_content)
    print("生成文件: %s", asm_lsp_file)

    -- 3. 创建 Makefile
    local makefile_content = '# Makefile for NASM project\
BUILD:=./build\
IMAGE:= "hd.img"\
\
all: ${BUILD}/boot/boot.bin\
\trm -f $(IMAGE)\
\tbximage -q -hd=16 -func=create -sectsize=512 -imgmode=flat $(IMAGE)\
\tdd if=${BUILD}/boot/boot.bin of=hd.img bs=512 seek=0 count=1 conv=notrunc\
\
${BUILD}/boot/boot.bin: src/boot/boot.asm\
\tmkdir -p ${BUILD}\
\tmkdir -p ${BUILD}/boot\
\tnasm $< -o $@ -l ${BUILD}/boot/boot.lst\
\
clean:\
\trm -f $(IMAGE)\
\trm -rf ${BUILD}\
\
bochs: all\
\tbochs -q -f bochsrc\
\
.PHONY: all clean bochs'
    local makefile_file = path.join(project_root, "makefile")
    io.writefile(makefile_file, makefile_content)
    print("生成文件: %s", makefile_file)

    -- 4. 创建 xmake.lua
    local xmake_lua_content = [[-- xmake.lua for NASM project
local image = "hd.img"

-- 自定义规则：汇编文件编译
rule("asm")
do
  set_extensions(".asm", ".s")

  on_build_file(function(target, sourcefile, opt)
    print("sourcefile: %s", sourcefile)
    -- 获取源文件相对路径，用于保持目录结构，不要 src
    local relpath = path.relative(sourcefile, "src")
    local obj = path.join("$(buildir)", path.directory(relpath), path.basename(sourcefile) .. ".bin")
    local lst = path.join("$(buildir)", path.directory(relpath), path.basename(sourcefile) .. ".lst")
    -- 确保目标目录存在
    os.mkdir(path.directory(obj))
    -- 编译汇编文件
    os.run("nasm %s -o %s -l %s", sourcefile, obj, lst)
  end)

  on_clean(function(target)
    os.rm("$(buildir)")
  end)
end
rule_end()

target("compile", function()
  set_kind("object")
  add_files("src/**.asm")
  add_rules("asm")
end)

-- 主目标：构建硬盘镜像
target("hdimg", function()
  set_kind("phony")
  add_deps("compile")

  on_build(function(target)
    print("Image on build")
    -- 删除旧的镜像文件
    if os.isfile(image) then
      os.rm(image)
    end
    -- 创建新的硬盘镜像
    os.exec("bximage -q -hd=16 -func=create -sectsize=512 -imgmode=flat %s", image)
    os.exec("dd if=build/boot/boot.bin of=%s bs=512 seek=0 count=1 conv=notrunc", image)
    print("写入 image 完成.")
  end)

  on_clean(function(target)
    -- 清理时删除镜像文件
    if os.isfile(image) then
      os.rm(image)
    end
  end)
end)

-- Bochs 模拟器目标
target("bochs", function()
  set_kind("phony")
  set_default(true)
  add_deps("hdimg") -- 依赖 hdimg 目标

  on_build(function(target)
    os.exec("bochs -q -f bochsrc")
  end)
end)
]]
    local xmake_lua_file = path.join(project_root, "xmake.lua")
    io.writefile(xmake_lua_file, xmake_lua_content)
    print("生成文件: %s", xmake_lua_file)

    -- 5. 创建 bochsrc
    local bochsrc_content = [[# Bochs configuration file
megs: 32  # 分配32MB内存

# 硬盘配置（IDE接口）
ata0: enabled=1, ioaddr1=0x1f0, ioaddr2=0x3f0, irq=14
ata0-master: type=disk, path="hd.img", mode=flat

# 启动设置（从硬盘启动）
boot: disk

# 显示配置
display_library: x, options="gui_debug"

# 调试配置（开启魔术断点）
magic_break: enabled=1
# debugger_log: bochs_debug.log
log: bochsout.txt

# 其他基本配置
mouse: enabled=0
# 这个配置有问题，会导致 buffer overflow
# keyboard: keymap=/usr/local/share/bochs/keymaps/x11-pc-us.map
]]
    local bochsrc_file = path.join(project_root, "bochsrc")
    io.writefile(bochsrc_file, bochsrc_content)
    print("生成文件: %s", bochsrc_file)

    print("项目 '%s' 生成成功！", target_name)
    print("项目结构：")
    print("  " .. target_name .. "/")
    print("  ├── src/boot/")
    print("  │   └── boot.asm")
    print("  ├── .asm-lsp.toml")
    print("  ├── bochsrc")
    print("  ├── makefile")
    print("  └── xmake.lua")
    print("接下来，你可以：")
    print("  - 进入项目目录: cd " .. target_name)
    print("  - 使用 Xmake 构建运行: xmake")
    print("  - 使用 Make 构建运行: make bochs")
  end)
end
